﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MINERP.BLL.CustomerManage;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraGrid;
using Leadtools.WinForms;
using Leadtools.Codecs;
using Leadtools;
using System.Drawing;
using System.Data;
using MINERP.COM;

namespace MINERP.CustomerManage.Controller
{
    public  class OrderInfoController : ControllerBase
    {

        #region //Private fields

        private OrderInfoManagerBLL         _bll = new OrderInfoManagerBLL();

        private GridControl                 _grid = null;

        private List<OrderInfoEntity>       _list = null;

        /// <summary>
        /// 照片的浏览器
        /// </summary>
        private RasterThumbnailBrowser      _imgaeBrowser = null;

        /// <summary>
        /// 当前产品实体对象
        /// </summary>
        private OrderInfoEntity             _focusObj = null;

        /// <summary>
        /// 当前产品的显示VIEW
        /// </summary>
        private GridView                    _focusView = null;

        /// <summary>
        /// 当前产品的订单ID
        /// </summary>
        private int                         _currentBagID = 0;
        /// <summary>
        /// 
        /// </summary>
        private int                         _photoCount = 0;


        #endregion


        #region //Public Priorities

        internal GridControl Grid
        {
            set
            {
                this._grid = value;
            }
        }

        /// <summary>
        /// 图像浏览器
        /// </summary>
        internal RasterThumbnailBrowser ImagerBrowser
        { 
            set
            {
                this._imgaeBrowser = value;
            }
        }

        internal GridView FocusView
        {
            set
            {
                this._focusView = value;
            }
        }

        /// <summary>
        /// 当前产品的ID
        /// </summary>
        internal int FocusID
        {
            get
            {
                if (this._focusObj != null)
                    return this._focusObj.OrderProductId;

                return 0;
            }
        }
        /// <summary>
        /// 得到产品的数量
        /// </summary>
        public int PhotoCount
        {
            get
            {
                if (FocusID == 0)
                {
                    return 0;
                }

                return this._photoCount;
            }
        }

        #endregion


        #region //Public Methods

        /// <summary>
        /// 设置产品的背景色
        /// </summary>
        /// <param name="e"></param>
        internal void SetSubBackColor(RowStyleEventArgs e)
        {
            e.Appearance.BackColor = Color.LightBlue;
            e.Appearance.BackColor2 = Color.LightBlue;
        }

        /// <summary>
        /// 通过订单得到产品
        /// </summary>
        /// <param name="bagID"></param>
        /// <returns></returns>
        internal List<OrderInfoEntity> GetOrderInfoByBagCode(int bagID)
        {
            this._currentBagID = bagID;
            OrderInfoManagerBLL bll = new OrderInfoManagerBLL();
            _list = bll.GetOrderInfoByBagCode(bagID);
            return _list;
        }

        /// <summary>
        /// 通过订单得到产品(备份)
        /// </summary>
        /// <param name="bagID"></param>
        /// <returns></returns>
        internal List<OrderInfoEntity> GetOrderInfoByBagCode_bk(int bagID)
        {
            this._currentBagID = bagID;
            OrderInfoManagerBLL bll = new OrderInfoManagerBLL();
            _list = bll.GetOrderInfoByBagCode_bk(bagID);
            return _list;
        }
        /// <summary>
        /// 得到产品的所有照片信息
        /// </summary>
        /// <param name="id"></param>
        internal void GetImageList(List<string> pathList)
        {
            //清空计数器
            this._photoCount = 0;

            this._imgaeBrowser.Items.Clear();

            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            for (int j = 0; j < pathList.Count; j++)
            {
                if (j % 2 == 1)
                    continue;
                _photoCount++;
                RasterImageListItem item = new RasterImageListItem();

                string path = pathList[j];
                string code = pathList[j + 1];

                item.Image = this.GetOneRasterImage(path, codecs);
                item.Page = 1;
                if (string.Compare(string.Empty, path) != 0)
                {
                    //item.Text = path.Substring(path.LastIndexOf("\\")).Substring(2);
                    item.Text = code;
                    item.Tag = path;
                }
                if (item.Image != null)
                {
                    this._imgaeBrowser.Items.Add(item);
                    //j++;
                }
                j++;
            }

            codecs.Dispose();
            RasterCodecs.Shutdown();
        }

        #region //update methods

        internal void Update()
        {
            if (this._focusObj == null)
            {
                MessageBox.Show("请先编辑选中的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }

            //try
            //{
            //    if (_focusObj.IsDirty)
            //    {
            //        _focusObj.IsEdit = false;
            //        _bll.Update();
            //    }
            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show(e.Message);
            //    return;
            //}

            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        internal void UpdateEditStatus()
        {
            this._focusObj.IsEdit = true;

            this._bll.Update();
        }

        #endregion


        #region //Check Methods

        /// <summary>
        /// 检查用户要编辑的行是否为可编辑状态
        /// </summary>
        /// <returns></returns>
        internal bool CheckUsed()
        {
            this._focusObj = (OrderInfoEntity)this._focusView.GetFocusedRow();

            if (this._focusObj != null)
            {
                if (this._focusObj.IsEdit)
                {
                    MessageBox.Show("你选中的行别人正在编辑中，请稍后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 显示报警色
        /// </summary>
        /// <param name="e"></param>
        internal void CheckAlarm(object sender,RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            OrderInfoEntity item = view.GetRow(e.RowHandle) as OrderInfoEntity;

            if (item != null)
            {
                if (item.StatusValue == (int)OrderInfoStatus.Completed)
                {
                    e.Appearance.BackColor = Color.Empty;
                    e.Appearance.BackColor2 = Color.Empty;
                    return;
                }
                //如果订单已经完成则不着色
                if (item.StatusValue != (int)OrderInfoStatus.OverOrder)
                {
                    /*
                    if (item.PreCompleteTime <= DateTime.Now.AddHours(Properties.Settings.Default.AlarmTime))
                    {
                        e.Appearance.BackColor = Color.LightPink;
                        e.Appearance.BackColor2 = Color.LightPink;
                    }
                    if (item.StatusValue == (int)OrderInfoStatus.Stop)
                    {
                        e.Appearance.BackColor = Color.LightSlateGray;
                        e.Appearance.BackColor2 = Color.LightSlateGray;
                    }*/
                    if (item.Priority <= 6)
                    {
                        e.Appearance.BackColor = Color.Empty;
                        e.Appearance.BackColor2 = Color.Empty;
                    }
                    else if (item.Priority > 6 && item.Priority <= 10)
                    {
                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                    else if (item.Priority == 11)
                    {
                        e.Appearance.BackColor = Color.Red;
                        e.Appearance.BackColor2 = Color.Red;
                    }
                    if (item.Status.Contains("删除"))
                    {
                        e.Appearance.BackColor = Color.Gray;
                    }
                }

            }
        }

        #endregion

        #endregion

        #region //报表

        /// <summary>
        /// 填充订单包的订单产品
        /// </summary>
        /// <param name="bagid"></param>
        /// <returns></returns>
        internal DataTable FillSubData(int bagid)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("OrderProductCode");
            dt.Columns.Add("OrderProductName");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("CtmName");
            dt.Columns.Add("CompleteTime");
            dt.Columns.Add("status");
            dt.Columns.Add("OrderPath");
            dt.Columns.Add("OrilOrderPath");
            dt.Columns.Add("Width");
            dt.Columns.Add("Height");
            dt.Columns.Add("Remark");
            dt.Columns.Add("productNum");
            dt.Columns.Add("PageNum");

            List<OrderInfoEntity> collection = this._bll.GetOrderInfoByBagCode(bagid);

            foreach (OrderInfoEntity item in collection)
            {
                DataRow row = dt.Rows.Add();

                row["OrderProductCode"] = item.OrderProductCode;
                row["OrderProductName"] = item.OrderProductName;
                row["ProductName"] = item.ProductName;
                row["CtmName"] = item.CtmName;
                if (item.CompleteTime != null)
                {
                    row["CompleteTime"] = item.CompleteTime;
                }
                else
                {
                    row["CompleteTime"] = "未完成";   
                }
                row["status"] = item.Status;
                row["OrderPath"] = item.OrderPath;
                row["OrilOrderPath"] = item.OrilOrderPath;
                row["Width"] = item.Width;
                row["Height"] = item.Height;
                row["Remark"] = item.Remark;
                row["productNum"] = item.productNum;
                row["PageNum"] = item.PageNum;
            }

            return dt;
        }

        #endregion

        #region //helper function

        private RasterImage GetOneRasterImage(string path,RasterCodecs codecs)
        {
            CodecsThumbnailOptions options = new CodecsThumbnailOptions();
            options.Resample = true;
            options.LoadStamp = true;
            options.MaintainAspectRatio = true;
            RasterImage img = null;

            try
            {
                img = codecs.ReadThumbnail(path, options, 1);
                if (img == null)
                {
                    img = codecs.Load(path);                //缩略图不存在就加载原图
                }
            }
            catch 
            {
                try
                {
                    img = new RasterImage(Image.FromFile(path));
                }
                catch
                {
                    img = new RasterImage(Image.FromFile(Application.StartupPath + "\\" + "PhotoNotFind.jpg"));
                }
            }

            return img;
        }

        #endregion


        #region //设置产品的生产状态

        internal bool SetUnProductStatus()
        {
            if (this._focusView != null)
            {
                this._focusObj = this._focusView.GetFocusedRow() as OrderInfoEntity;


                if (_focusObj != null)
                {
                    if (_focusObj.StatusValue == (int)OrderInfoStatus.Stop)
                    {
                        return false;
                    }
                    //把产品的状态改为停止状态
                    _focusObj.StatusValue = (int)OrderInfoStatus.Stop;

                }
            }

            return true;
        }
        /// <summary>
        /// 把还未完成的产品设置为正常生产状态
        /// </summary>
        internal void SetNormalStatus()
        {
            if (this._focusView != null)
            {
                this._focusObj = this._focusView.GetFocusedRow() as OrderInfoEntity;


                if (_focusObj != null)
                {
                    WorkOrderFlowListController flowController = new WorkOrderFlowListController();
                    //如果产品的生产状态是正常的状态
                    if (flowController.GetOrderInfoStatus(_focusObj.OrderProductId))
                    {
                        //如果产品还没有结单把产品的状态改为停止前的生产状态
                        if (_focusObj.StatusValue != (int)OrderInfoStatus.OverOrder)
                        {
                            _focusObj.StatusValue = (int)OrderInfoStatus.Doing;
                        }
                    }
                    else 
                    {
                        //如果不是正常状态则修改为异常状态
                        _focusObj.StatusValue = (int)OrderInfoStatus.Error;
                    }

                }
            }
        }


        /// <summary>
        /// 判断订单下未生产的产品的数量
        /// </summary>
        /// <param name="bagid"></param>
        internal int GetStopInfoCountByBag(int bagid)
        {
            return _bll.GetInfoStopCountByBag(bagid);
        }

        /// <summary>
        /// 得到订单下的所有产品的数量
        /// </summary>
        /// <param name="bagid"></param>
        /// <returns></returns>
        internal int GetInfoCountByBag(int bagid)
        {
            return _bll.GetInfoCountByBag(bagid);
        }

        #endregion
    }
}
